package code.c02_list.sqList;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author thinkpad - 83start
 * @version v1.0
 * @create 2022/9/12 9:22
 * @package code.c02_list.classwork.examples
 * @description 有若干个学生记录，每个记录包含姓名和年龄，用类ArrayList的对象，存放。
 * 分别采用以上三种排序方法是心啊按年龄的递增排序，按姓名的递增排序和按姓名的递减排序。并用相关数据进行测试
 */

public class Exam_2_9 {
    public static void main(String[] args) {
        List<Student> studentList = new ArrayList<>();
        studentList.add(new Student("john",32));
        studentList.add(new Student("java",78));
        studentList.add(new Student("python",33));
        studentList.add(new Student("html",31));
        studentList.add(new Student("css",3));
        studentList.add(new Student("vue",12));

        System.out.println("初始序列：" + studentList);


        // 排序方法1：
        List<Student> copyStudentList = new ArrayList<>();
       copyStudentList.addAll(studentList);

        Collections.sort(copyStudentList);
        System.out.println("按年龄增需排列：" + copyStudentList);

        // 排序方法2：
        copyStudentList.clear();
        copyStudentList.addAll(studentList);
        Collections.sort(copyStudentList, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
               return o1.getName().compareTo(o2.getName());
            }
        });
        System.out.println("按姓名增序：" + copyStudentList);

        // 排序方法3：
        copyStudentList.clear();
        copyStudentList.addAll(studentList);
        copyStudentList.sort(Comparator.comparing(Student::getName).reversed());
        System.out.println("按姓名降序：" + copyStudentList);
    }
}

/**
 * 都不敢图个学生对象
 */
class Student implements Comparable<Student> {
    public String name;
    public Integer age;

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    // 实现按 age 递增排序
    @Override
    public int compareTo(Student o) {
        return this.age.compareTo(o.age);
    }
}
